import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/simple-test',
    name: 'SimpleTest',
    component: () => import('@/views/SimpleTest.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/simple-login',
    name: 'SimpleLogin',
    component: () => import('@/views/SimpleLogin.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/simple-login-vue',
    name: 'SimpleLoginVue',
    component: () => import('@/views/Login/SimpleLogin.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/BasicLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: { title: '首页', icon: 'House' }
      },
      {
        path: 'interface',
        name: 'Interface',
        component: () => import('@/views/Interface/index.vue'),
        meta: { title: '接口广场', icon: 'Connection' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile/index.vue'),
        meta: { title: '个人中心', icon: 'User' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings/index.vue'),
        meta: { title: '设置', icon: 'Setting' }
      },
      {
        path: 'admin',
        name: 'Admin',
        component: () => import('@/views/Admin/index.vue'),
        meta: { title: '管理后台', icon: 'Setting', requiresAdmin: true },
        children: [
          {
            path: 'interface-info',
            name: 'InterfaceInfo',
            component: () => import('@/views/Admin/InterfaceInfo/index.vue'),
            meta: { title: '接口管理' }
          },
          {
            path: 'interface-analysis',
            name: 'InterfaceAnalysis',
            component: () => import('@/views/Admin/InterfaceAnalysis/index.vue'),
            meta: { title: '接口分析' }
          }
        ]
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 确保 Pinia 已经初始化
  const userStore = useUserStore()
  
  // 初始化用户信息
  userStore.initUserInfo()
  
  if (to.meta.requiresAuth !== false && !userStore.isLoggedIn) {
    next('/login')
  } else if (to.meta.requiresAdmin && !userStore.isAdmin) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
